package com.mnnu.filter;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.dialect.rowbounds.HerdDBRowBoundsDialect;
import com.google.gson.JsonObject;
import com.mnnu.pojo.Result;
import com.mnnu.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Slf4j
//@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse rep = (HttpServletResponse) servletResponse;

        //获取请求url
        String requestURL = req.getRequestURL().toString();
        log.info("请求的url:{}", requestURL);

        //判断url是否包含login，如果包含则直接放行通过
        if(requestURL.contains("login")) {
            log.info("登录操作 放行...");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        //获取请求头中的令牌（token）
        String jwt = req.getHeader("token");

        //判断token是否存在，若不存在则直接返回错误结果（未登录）
        if(!StringUtils.hasLength(jwt)) {
            log.info("请求头token为空！");
            Result error = Result.error("NOT_LOGIN");

            //手动将转换 对象-->json ------------>阿里巴巴fastJSON
            String notLogin = JSONObject.toJSONString(error);
            rep.getWriter().write(notLogin);
            return;
        }

        //解析token，如果解析失败则放回错误结果（未登录）
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) { //解析jwt令牌失败
            e.printStackTrace();

            log.info("解析jwt令牌失败！");
            Result error = Result.error("NOT_LOGIN");
            //手动将转换 对象-->json ------------>阿里巴巴fastJSON
            String notLogin = JSONObject.toJSONString(error);
            rep.getWriter().write(notLogin);
            return;

        }

        //放行通过
        filterChain.doFilter(servletRequest, servletResponse);

    }
}
